package org.sxm.cloud.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/** 
* @Description: 工具类注入，获取应用上下文
* @Author: xmSheng
* @Date: 2024/1/22
*/

@Component
public class AppContext implements ApplicationContextAware{
	private static ApplicationContext applicationContext;

	private AppContext() {
	}

	/**
	 * spring ApplicationContext
	 * 
	 * @return spring ApplicationContext
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public  void setApplicationContext(ApplicationContext applicationContext) {
		AppContext.applicationContext = applicationContext;
	}
	
	public static <T> T getBean(Class<T> clzz) {
		if(applicationContext != null) {
			return (T)applicationContext.getBean(clzz);
		}
		return null;
	}
	
	public static Object getBean(String beanName) {
		if(applicationContext != null) {
			return applicationContext.getBean(beanName);
		}
		return null;
	}
	
	public static <T> Map<String,T> getBeanOfType(Class<T> clzz){
		if(applicationContext != null) {
			return applicationContext.getBeansOfType(clzz);
		}
		return new HashMap<String,T>();
	}
}
